package com.easemob.cases.ui;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.czy.owner.R;
import com.czy.owner.entity.MessageContacts;
import com.czy.owner.global.Constants;
import com.czy.owner.db.UserHelper;
import com.czy.owner.ui.message.ContactsPanelActivity;
import com.czy.owner.ui.message.GroupDetailsActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.StringUtils;
import com.czy.owner.utils.disk.DiskLruCacheHelper;
import com.czy.owner.widget.DialogCall;
import com.czy.owner.widget.UniversalDialog;
import com.easemob.cases.MessageHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.ui.EaseChatFragment.EaseChatFragmentHelper;
import com.hyphenate.easeui.ui.ImageGridActivity;
import com.hyphenate.easeui.ui.VideoCallActivity;
import com.hyphenate.easeui.ui.VoiceCallActivity;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.PathUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.functions.Consumer;

public class ChatFragment extends EaseChatFragment implements EaseChatFragmentHelper {

    // constant start from 11 to avoid conflict with constant in base class
    private static final int ITEM_VIDEO = 11;
    //private static final int ITEM_FILE = 12;
    private static final int ITEM_VOICE_CALL = 13;
    private static final int ITEM_VIDEO_CALL = 14;

    private static final int REQUEST_CODE_SELECT_VIDEO = 11;
    private static final int REQUEST_CODE_SELECT_FILE = 12;
    private static final int REQUEST_CODE_GROUP_DETAIL = 13;
    private static final int REQUEST_CODE_CONTEXT_MENU = 14;
    private static final int REQUEST_CODE_SELECT_AT_USER = 15;


    private static final int MESSAGE_TYPE_SENT_VOICE_CALL = 1;
    private static final int MESSAGE_TYPE_RECV_VOICE_CALL = 2;
    private static final int MESSAGE_TYPE_SENT_VIDEO_CALL = 3;
    private static final int MESSAGE_TYPE_RECV_VIDEO_CALL = 4;

    //red packet code : 红包功能使用的常量
    /*private static final int MESSAGE_TYPE_RECV_RED_PACKET = 5;
    private static final int MESSAGE_TYPE_SEND_RED_PACKET = 6;
    private static final int MESSAGE_TYPE_SEND_RED_PACKET_ACK = 7;
    private static final int MESSAGE_TYPE_RECV_RED_PACKET_ACK = 8;
    private static final int REQUEST_CODE_SEND_RED_PACKET = 16;
    private static final int ITEM_RED_PACKET = 16;*/
    //end of red packet code


    /*
    private MessageContacts mMessageContact = null;*/
    DiskLruCacheHelper cacheHelper = null;
    private List<MessageContacts> mContactsList = new ArrayList<>();

    protected String[] needPermissions = {
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA
    };
    private static final int PERMISSION_REQUEST_CODE_RECORD = 21;
    private static final int PERMISSION_REQUEST_CODE_RECORD_AND_CAMERA = 22;

    /**
     * if it is chatBot
     */
    private boolean isRobot;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void setUpView() {
        setChatFragmentListener(this);

        super.setUpView();
        // set click listener
        titleBar.setLeftLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        if (chatType == EaseConstant.CHATTYPE_SINGLE) {
            titleBar.setRightImageResource(R.mipmap.icon_call_white);
            try {
                cacheHelper = new DiskLruCacheHelper(getContext());
            } catch (IOException e) {
                e.printStackTrace();
            }

            String dataSrc = null;
            if (cacheHelper != null) {
                dataSrc = cacheHelper.getAsString(UserHelper.getInstance().getUserAccount() + "_contacts");
            }
            if (TextUtils.isEmpty(dataSrc)) {
                RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_ADDRESS_BOOK);
                params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(getContext()).getSession());
                params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(getActivity(), UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
                x.http().post(params, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(getActivity(), result);
                        if (data != null) {
                            if (cacheHelper != null) {
                                cacheHelper.put(UserHelper.getInstance().getUserAccount() + "_contacts", data, 3600);
                            }
                            getCurrentMessageContact(data);
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            } else {
                getCurrentMessageContact(dataSrc);
            }

        }

        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        EMClient.getInstance().groupManager().getGroupFromServer(toChatUsername);
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        if (Constants.IM_KEY_STORE_NOTICE.equals(toChatUsername) || Constants.IM_KEY_SYSTEM_NOTICE.equals(toChatUsername) || Constants.IM_KEY_SYSTEM_TIPS.equals(toChatUsername) || Constants.IM_KEY_PUSH_NOTICE.equals(toChatUsername)) {
            //titleBar.setRightLayoutVisibility(View.GONE);
            titleBar.setRightImageResource(R.drawable.ease_mm_title_remove);
            titleBar.setRightLayoutClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    String msg = getResources().getString(R.string.Whether_to_empty_all_chats);
                    new EaseAlertDialog(getActivity(), null, msg, null, new EaseAlertDialog.AlertDialogUser() {

                        @Override
                        public void onResult(boolean confirmed, Bundle bundle) {
                            if (confirmed) {
                                EMClient.getInstance().chatManager().deleteConversation(toChatUsername, true);
                                messageList.refresh();
                            }
                        }
                    }, true).show();
                }
            });

            inputMenu.setVisibility(View.GONE);
        }
    }

    private void getCurrentMessageContact(String dataSrc) {
        Gson gson = new Gson();
        mContactsList = gson.fromJson(dataSrc, new TypeToken<List<MessageContacts>>() {
        }.getType());
        /*for (int i = 0; i < mContactsList.size(); i++) {
            if (!TextUtils.isEmpty(mContactsList.get(i).getImKey()) && mContactsList.get(i).getImKey().equals(toChatUsername)) {
                mMessageContact = mContactsList.get(i);
                return;
            }
        }*/
    }

    private MessageContacts getMessageContact(String username) {
        for (int i = 0; i < mContactsList.size(); i++) {
            if (!TextUtils.isEmpty(mContactsList.get(i).getImKey()) && mContactsList.get(i).getImKey().equals(username)) {
                return mContactsList.get(i);
            }
        }
        return null;
    }

    @Override
    protected void emptyHistory() {
        //super.emptyHistory();
        EaseUser easeUser = EaseUserUtils.getUserInfo(toChatUsername);
        if (toChatUsername.length() > 3 && "adm".equals(toChatUsername.substring(0, 3)) && StringUtils.isEmpty(easeUser.getPhone())) {
            easeUser.setPhone(toChatUsername.substring(3, toChatUsername.length()));
        }
        if (easeUser != null) {
            Pattern p = Pattern.compile("[\\d|\\-]+");
            final Matcher m = p.matcher(StringUtils.getString(easeUser.getPhone(), ""));
            if (m.find() && !TextUtils.isEmpty(m.group(0))) {
                final DialogCall dialogCall = new DialogCall(getContext(), R.layout.dialog_call);
                dialogCall.setContent("" + m.group(0)).setListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PhoneUtils.checkCallPermission(getContext(), m.group(0));
                        dialogCall.dismiss();
                    }
                }).show();
            } else {
                PhoneUtils.ShowToastMessage(getContext(), "此联系人,未设置联系电话!");
            }
        } else {
            PhoneUtils.ShowToastMessage(getContext(), "没有获取到该联系人资料,请稍候!");
        }

/*        Pattern p = Pattern.compile("\\d+");
        final Matcher m = p.matcher(EMClient.getInstance().getCurrentUser());
        if (m.find() && !TextUtils.isEmpty(m.group(0))) {
            //System.out.println(m.group(0));
            final DialogCall dialogCall = new DialogCall(getContext(), R.layout.dialog_call);
            dialogCall.setContent("" + m.group(0)).setListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PhoneUtils.checkCallPermission(getContext(), m.group(0));
                    dialogCall.dismiss();
                }
            }).show();
        }*/
    }

    @Override
    protected void registerExtendMenuItem() {
        //use the menu in base class
        super.registerExtendMenuItem();
        //extend menu items
        if (EaseUserUtils.getUserInfo(toChatUsername).getUserType() != EaseUser.USER_TYPE_SYSTEM) {
            inputMenu.registerExtendMenuItem(R.string.attach_video, R.drawable.em_chat_video_selector, ITEM_VIDEO, extendMenuItemClickListener);

            //inputMenu.registerExtendMenuItem(R.string.attach_file, R.drawable.em_chat_file_selector, ITEM_FILE, extendMenuItemClickListener);
            if (chatType == EaseConstant.CHATTYPE_SINGLE) {
                inputMenu.registerExtendMenuItem(R.string.attach_voice_call, R.drawable.em_chat_voice_call_selector, ITEM_VOICE_CALL, extendMenuItemClickListener);
                inputMenu.registerExtendMenuItem(R.string.attach_video_call, R.drawable.em_chat_video_call_selector, ITEM_VIDEO_CALL, extendMenuItemClickListener);
            }
        }
        //聊天室暂时不支持红包功能
        //red packet code : 注册红包菜单选项
        /*if (chatType != Constant.CHATTYPE_CHATROOM) {
            inputMenu.registerExtendMenuItem(R.string.attach_red_packet, R.drawable.em_chat_red_packet_selector, ITEM_RED_PACKET, extendMenuItemClickListener);
        }*/
        //end of red packet code
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
            switch (resultCode) {
            /*case ContextMenuActivity.RESULT_CODE_COPY: // copy
                clipboard.setPrimaryClip(ClipData.newPlainText(null,
                        ((EMTextMessageBody) contextMenuMessage.getBody()).getMessage()));
                break;
            case ContextMenuActivity.RESULT_CODE_DELETE: // delete
                conversation.removeMessage(contextMenuMessage.getMsgId());
                messageList.refresh();
                break;

            case ContextMenuActivity.RESULT_CODE_FORWARD: // forward
                Intent intent = new Intent(getActivity(), ForwardMessageActivity.class);
                intent.putExtra("forward_msg_id", contextMenuMessage.getMsgId());
                startActivity(intent);
                
                break;*/

                default:
                    break;
            }
        }
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SELECT_VIDEO: //send the video
                    if (data != null) {
                        int duration = data.getIntExtra("dur", 0);
                        String videoPath = data.getStringExtra("path");
                        File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
                        try {
                            FileOutputStream fos = new FileOutputStream(file);
                            Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                            ThumbBitmap.compress(CompressFormat.JPEG, 100, fos);
                            fos.close();
                            sendVideoMessage(videoPath, file.getAbsolutePath(), duration);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case REQUEST_CODE_SELECT_FILE: //send the file
                    if (data != null) {
                        Uri uri = data.getData();
                        if (uri != null) {
                            sendFileByUri(uri);
                        }
                    }
                    break;
                case REQUEST_CODE_SELECT_AT_USER:
                    if (data != null) {
                        String username = data.getStringExtra("username");
                        inputAtUsername(username, false);
                    }
                    break;
                //red packet code : 发送红包消息到聊天界面
            /*case REQUEST_CODE_SEND_RED_PACKET:
                if (data != null){
                    sendMessage(RedPacketUtil.createRPMessage(getActivity(), data, toChatUsername));
                }
                break;*/
                //end of red packet code
                default:
                    break;
            }
        }

    }

    @Override
    public void onSetMessageAttributes(EMMessage message) {
        if (isRobot) {
            //set message extension
            message.setAttribute("em_robot_message", isRobot);
        }

        // TODO 扩展字段 加入用户昵称和头像路径
        if (MessageHelper.getInstance().getUserProfileManager().getCurrentUserNick() != null || MessageHelper.getInstance().getUserProfileManager().getCurrentUserAvatar() != null) {
            message.setAttribute(MessageHelper.MESSAGE_EXT_NAME, MessageHelper.getInstance().getUserProfileManager().getCurrentUserNick());
            message.setAttribute(MessageHelper.MESSAGE_EXT_AVATAR, MessageHelper.getInstance().getUserProfileManager().getCurrentUserAvatar());
        }
    }

    @Override
    public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
        return new CustomChatRowProvider();
    }


    @Override
    public void onEnterToChatDetails() {
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
            if (group == null) {
                PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.gorup_not_found));
                return;
            }
            startActivityForResult(
                    (new Intent(getActivity(), GroupDetailsActivity.class).putExtra("groupId", toChatUsername)),
                    REQUEST_CODE_GROUP_DETAIL);
        }
    }

    @Override
    public void onAvatarClick(String username) {
        //handling when user click avatar
        //chatType == EaseConstant.CHATTYPE_SINGLE &&
        if (!username.equals(EMClient.getInstance().getCurrentUser()) && !username.equals(Constants.IM_KEY_STORE_NOTICE) && !username.equals(Constants.IM_KEY_SYSTEM_TIPS) && !username.equals(Constants.IM_KEY_PUSH_NOTICE)) {


            MessageContacts messageContacts = getMessageContact(username);
            if (messageContacts != null) {
                Intent intent = new Intent(getActivity(), ContactsPanelActivity.class);
                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, messageContacts);
                startActivity(intent);
            } else {

            }

        }
    }

    @Override
    public void onAvatarLongClick(String username) {
        //inputAtUsername(username);
    }


    @Override
    public boolean onMessageBubbleClick(EMMessage message) {
        //消息框点击事件，demo这里不做覆盖，如需覆盖，return true
        //red packet code : 拆红包页面
        /*if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)){
            RedPacketUtil.openRedPacket(getActivity(), chatType, message, toChatUsername, messageList);
            return true;
        }*/
        //end of red packet code
        return false;
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        //red packet code : 处理红包回执透传消息
        for (EMMessage message : messages) {
            EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
            String action = cmdMsgBody.action();//获取自定义action
            /*if (action.equals(RedPacketConstant.REFRESH_GROUP_RED_PACKET_ACTION)){
                RedPacketUtil.receiveRedPacketAckMessage(message);
                messageList.refresh();
            }*/
        }
        //end of red packet code
        super.onCmdMessageReceived(messages);
    }

    @Override
    public void onMessageBubbleLongClick(EMMessage message) {
        // no message forward when in chat room
        /*startActivityForResult((new Intent(getActivity(), ContextMenuActivity.class)).putExtra("message",message)
                .putExtra("ischatroom", chatType == EaseConstant.CHATTYPE_CHATROOM),
                REQUEST_CODE_CONTEXT_MENU);*/

        new UniversalDialog(getActivity()).builder().setTitle("删除信息")
                .setMsg("删除信息后不可恢复\n是否确定删除")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        conversation.removeMessage(contextMenuMessage.getMsgId());
                        messageList.refresh();

                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();

    }

    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
        switch (itemId) {
            case ITEM_VIDEO:
                // TODO 视频
                if (!EMClient.getInstance().isConnected()) {
                    PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.not_connect_to_server));
                } else {
                    Intent intent = new Intent(getActivity(), ImageGridActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
                }
                break;
        /*case ITEM_FILE: //file
            selectFileFromLocal();
            break;*/
            case ITEM_VOICE_CALL:
                //PhoneUtils.ShowToastMessage(getContext(), "Come Soon!ITEM_VOICE_CALL");
                startVoiceCall();
                break;
            case ITEM_VIDEO_CALL:
                //PhoneUtils.ShowToastMessage(getContext(), "Come Soon!ITEM_VIDEO_CALL");
                startVideoCall();
                break;
            //red packet code : 进入发红包页面
        /*case ITEM_RED_PACKET:
            RedPacketUtil.startRedPacketActivityForResult(this, chatType, toChatUsername, REQUEST_CODE_SEND_RED_PACKET);
            break;*/
            //end of red packet code
            default:
                break;
        }
        //keep exist extend menu
        return false;
    }

    /**
     * select file
     */
    protected void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) { //api 19 and later, we can't use this way, demo just select from images
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }

    private RxPermissions rxPermissions;

    /**
     * make a voice call
     */
    protected void startVoiceCall() {
        rxPermissions = new RxPermissions(getActivity());
        if (!EMClient.getInstance().isConnected()) {
            PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.not_connect_to_server));
        } else {
            // TODO 检测是否 有麦克风权限
            rxPermissions.request(Manifest.permission.RECORD_AUDIO)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(@NonNull Boolean aBoolean) throws Exception {
                            if (aBoolean) {
                                startActivity(new Intent(getActivity(), VoiceCallActivity.class).putExtra("username", toChatUsername)
                                        .putExtra("isComingCall", false));
                                MyLog.e("yang", "获取权限成功");
                            } else {
                                MyLog.e("yang", "获取权限失败");
                            }
                        }
                    });


//            if(checkPermissions(PERMISSION_REQUEST_CODE_RECORD,needPermissions[0])){
//                startActivity(new Intent(getActivity(), VoiceCallActivity.class).putExtra("username", toChatUsername)
//                        .putExtra("isComingCall", false));
//            }
            // voiceCallBtn.setEnabled(false);
            inputMenu.hideExtendMenuContainer();
        }
    }

    /**
     * make a video call
     */
    protected void startVideoCall() {
        if (!EMClient.getInstance().isConnected())
            PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.not_connect_to_server));
        else {
            // TODO 检测是否有麦克风权限和相机权限

            if (checkPermissions(PERMISSION_REQUEST_CODE_RECORD_AND_CAMERA, needPermissions[0], needPermissions[1])) {
                startActivity(new Intent(getActivity(), VideoCallActivity.class).putExtra("username", toChatUsername)
                        .putExtra("isComingCall", false));
            }
            // videoCallBtn.setEnabled(false);
            inputMenu.hideExtendMenuContainer();
        }
    }

    /**
     * chat row provider
     */
    private final class CustomChatRowProvider implements EaseCustomChatRowProvider {
        @Override
        public int getCustomChatRowTypeCount() {
            //here the number is the message type in EMMessage::Type
            //which is used to count the number of different chat row
            return 8;
        }

        @Override
        public int getCustomChatRowType(EMMessage message) {
            if (message.getType() == EMMessage.Type.TXT) {
                //voice call
                if (message.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_VOICE_CALL, false)) {
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE_CALL : MESSAGE_TYPE_SENT_VOICE_CALL;
                } else if (message.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_VIDEO_CALL, false)) {
                    //video call
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO_CALL : MESSAGE_TYPE_SENT_VIDEO_CALL;
                }
                /*//red packet code : 红包消息和红包回执消息的chat row type
                else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {
                    //发送红包消息
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_RED_PACKET : MESSAGE_TYPE_SEND_RED_PACKET;
                } else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {
                    //领取红包消息
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_RED_PACKET_ACK : MESSAGE_TYPE_SEND_RED_PACKET_ACK;
                }*/
                //end of red packet code
            }
            return 0;
        }

        @Override
        public EaseChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
            if (message.getType() == EMMessage.Type.TXT) {
                // TODO voice call or video call
                /*if (message.getBooleanAttribute(Constants.MESSAGE_ATTR_IS_VOICE_CALL, false) ||
                    message.getBooleanAttribute(Constants.MESSAGE_ATTR_IS_VIDEO_CALL, false)){
                    return new ChatRowVoiceCall(getActivity(), message, position, adapter);
                }
                //red packet code : 红包消息和红包回执消息的chat row
                else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {//发送红包消息
                    return new ChatRowRedPacket(getActivity(), message, position, adapter);
                } else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {//open redpacket message
                    return new ChatRowRedPacketAck(getActivity(), message, position, adapter);
                }*/
                //end of red packet code
            }
            return null;
        }

    }

    /**
     * @param permissions
     * @since 2.5.0
     */
    private boolean checkPermissions(int requestCode, String... permissions) {
        List<String> needRequestPermissonList = findDeniedPermissions(permissions);
        if (null != needRequestPermissonList
                && needRequestPermissonList.size() > 0) {
            int deniedCount = 0;
            for (int i = 0; i < needRequestPermissonList.size(); i++) {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), needRequestPermissonList.get(i))) {
                    deniedCount++;
                }
            }
            if (deniedCount == 0) {
                ActivityCompat.requestPermissions(getActivity(),
                        needRequestPermissonList.toArray(
                                new String[needRequestPermissonList.size()]),
                        requestCode);
            } else {
                showMissingPermissionDialog("麦克风或视频");
            }
            return false;
        }
        return true;
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(getActivity(),
                    perm) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.shouldShowRequestPermissionRationale(
                    getActivity(), perm)) {
                needRequestPermissonList.add(perm);
            }
        }
        return needRequestPermissonList;
    }

    /**
     * 检测是否说有的权限都已经授权
     *
     * @param grantResults
     * @return
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE_RECORD:
                if (!verifyPermissions(paramArrayOfInt)) {
                    showMissingPermissionDialog("麦克风");
                } else {
                    startVoiceCall();
                }
                break;
            case PERMISSION_REQUEST_CODE_RECORD_AND_CAMERA:
                if (!verifyPermissions(paramArrayOfInt)) {
                    showMissingPermissionDialog("麦克风或相机");
                } else {
                    startVideoCall();
                }
                break;
        }
    }

    /**
     * 显示提示信息
     *
     * @since 2.5.0
     */
    private void showMissingPermissionDialog(String strTips) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("提示");
        builder.setMessage("当前应用缺少" + strTips + "权限。\n请点击设置->权限->打开所需权限。");

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        finish();
                    }
                });

        builder.setPositiveButton(R.string.setting,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }

    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
        startActivity(intent);
    }
}
